import React, { useContext, useState, useEffect, useRef } from 'react';
import { Table, Button, Popconfirm, Form, Upload, Space, message } from 'antd';
import { componentsMap } from '@/utils/util';
import moment from 'moment';
const EditableContext = React.createContext(null);
import { DeleteFilled, UploadOutlined } from '@ant-design/icons';
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  type,
  rules = {},
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    if (type === 'datepicker' && record[dataIndex]) {
      form.setFieldsValue({
        [dataIndex]: moment(record[dataIndex]),
      });
      return;
    }
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      if (type === 'datepicker') {
        const doTime = values.doTime ? values.doTime.format('YYYY-MM-DD') : '';
        handleSave({ ...record, ...values, doTime });
        return;
      }
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
      handleSave({ ...record, errInfo });
    }
  };

  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `请输入${title}`,
          },
          rules,
        ]}
      >
        {componentsMap(type, {
          onPressEnter: save,
          onBlur: save,
          ref: inputRef,
        })}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    const jwt = localStorage.getItem('jwt');
    this.columns = [
      ...props.columns,
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        render: (_, record) =>
          this.state.dataSource.length >= 1 ? (
            <Space>
              <Upload
                action={'/jiaotong' + props.uploadUrl}
                showUploadList={false}
                beforeUpload={this.beforeUpload}
                onChange={(file) => this.handleUpload(file, record.key)}
                headers={{ jwt }}
              >
                <Button type="link" icon={<UploadOutlined />}></Button>
              </Upload>

              <Popconfirm
                title="是否确定删除?"
                onConfirm={() => this.handleDelete(record.id)}
              >
                <Button type="link" icon={<DeleteFilled />}></Button>
              </Popconfirm>
            </Space>
          ) : null,
      },
    ];
    this.state = {
      dataSource: [],
      count: 0,
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.defaultData) {
      this.setState({
        dataSource: [...nextProps.defaultData],
      });
    }
  }
  handleDelete = (key) => {
    const dataSource = [...this.state.dataSource];
    this.setState({
      dataSource: dataSource.filter((item) => item.id !== key),
    });
  };
  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      ...this.props.newData,
      id: count,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
  };
  handleSave = (row) => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex((item) => row.id === item.id);
    const item = newData[index];
    // item.doTime = item.doTime ? item.doTime.format('YYYY-MM-DD') : item.doTime;
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({
      dataSource: newData,
    });
  };
  beforeUpload(file) {
    const options = {
      // fileTypes: ['image/jpeg', 'image/png', 'image/jpg'],
      maxSize: 50,
      // acceptMessage: '图片',
    };
    // const isIncudeType = options.fileTypes.includes(file.type);
    // if (!isIncudeType && !ispassed) {
    //   message.error('只能上传' + options.acceptMessage + '格式!');
    // }

    const isMaxSize = file.size / 1024 / 1024 < options.maxSize;
    if (!isMaxSize && !ispassed) {
      message.error('文件大小不能超过' + options.maxSize + 'M!');
    }
    return isMaxSize;
  }
  handleUpload({ file }, key) {
    if (file.status === 'done') {
      if (!file.response) {
        message.error('文件上传失败，请稍后重试！');
      } else if (file.response) {
        const newData = [...this.state.dataSource];
        const index = newData.findIndex((item) => key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          originalFileName: file.response.t.originalFileName,
          fileName: file.response.t.fileName,
        });
        this.setState({
          dataSource: newData,
        });
      } else {
        message.error(file.response.msg);
      }
    }
  }
  getData = () => {
    return this.state.dataSource;
  };

  // static getDerivedStateFromProps(nextProps, prevState) {
  //   const { defaultData } = nextProps;
  //   // 当传入的defaultData发生变化的时候，更新state
  //   if (prevState.defaultData!==defaultData&&defaultData) {
  //     console.log(1);
  //     return {
  //       dataSource: [...defaultData],
  //     };
  //   }
  //   // 否则，对于state不进行任何操作
  //   return null;
  // }
  render() {
    const { dataSource } = this.state;
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          rules: col.rules,
          type: col.type,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <div>
        <Button
          onClick={this.handleAdd}
          type="primary"
          style={{
            margin: 16,
            float: 'right',
          }}
        >
          新增
        </Button>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          pagination={false}
          rowKey="id"
        />
      </div>
    );
  }
}
EditableTable.defaultProps = {
  columns: [],
};
export default EditableTable;
